package org.cqust.backend.config.advice;

import io.swagger.v3.oas.annotations.Hidden;
import jakarta.annotation.Nonnull;
import org.cqust.backend.common.ApiResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回结果，将响应标头设为与ApiResult相同的Code
 */
@Hidden
@ControllerAdvice
public class ApiResultResponseAdvice implements ResponseBodyAdvice<ApiResult<?>> {

    @Override
    public boolean supports(MethodParameter returnType,@Nonnull Class converterType) {
        // 只对ApiResult类型的返回值进行处理
        return ApiResult.class.isAssignableFrom(returnType.getParameterType());
    }
    @Override
    @Nonnull
    public ApiResult<?> beforeBodyWrite(@Nonnull ApiResult<?> body,
                                        @Nonnull MethodParameter returnType,
                                        @Nonnull MediaType selectedContentType,
                                        @Nonnull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                        @Nonnull ServerHttpRequest request,
                                        @Nonnull ServerHttpResponse response) {
        //根据Result-Code设置响应头
        response.setStatusCode(HttpStatusCode.valueOf(body.getCode()));
        // 添加CORS头
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        response.getHeaders().add("Access-Control-Allow-Headers", "*");

        return body;
    }
}
